import $ from 'jquery'

export default{
	ajaxPost: function(url,data,successback,errerback){
		getAccessToken(function(){
			ajax(url,data,"POST",true,successback,errerback);
		},errerback);
	},
	ajaxGet: function(url,data,isasync,successback,errerback){
		ajax(url,data,"Get",isasync,successback,errerback);
	},
	getAccessToken:function(sucCallback,errorback){
		var token = sessionStorage.getItem("wxOpenId");
	    var customerId = sessionStorage.getItem("customerId");
	
	    if (token && customerId) {
	        if (sucCallback) {
	            sucCallback();
	        }
	        return;
	    }
	
	    var code = getcode();
	    if (code) {
	        ajax("https://www.iqinyou.cn/o/wx/mp/oauth?code="+code+"&state=1", "","Get",true, function (d) {
	            if (d.status == 0) {
	                sessionStorage.setItem("wxOpenId",d.wxOpenId);
	                sessionStorage.setItem("customerId",d.customerId);
	                sessionStorage.setItem("customerHeadImg",d.portraitUrl);
	                if (sucCallback) {
	                    sucCallback();
	                }
	            } 
	        },function (request, textStatus, errorThrown) {
				if(errorback)
					errorback(request,textStatus,errorThrown);
			});
	    }
	}
};

function getcode()
{
	var code = getQueryString("code");
    if (!code) {
        var obj = {
            appid: "wx68acbff9c03f9936",
            redirect_uri: "",
            response_type: "code",
            scope: "snsapi_userinfo",
            state: "1"
        }
        var getcodeparas = $.extend(obj, {
            redirect_uri: window.location.href
        });

        window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" + perapara(getcodeparas,true) + "#wechat_redirect";
            
    } else {
        return code;
    }
}

function getQueryString(val)
{
	var reg = new RegExp("(^|&)" + val + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]);
    return null;
}

function perapara(objvalues, isencode)
{
	 var parastring = "";
        for (var key in objvalues) {
            isencode = isencode || false;
            if (isencode) {
                parastring += (key + "=" + encodeURIComponent(objvalues[key]) + "&");
            } else {
                parastring += (key + "=" + objvalues[key] + "&");
            }
        }
        parastring = parastring.substr(0, parastring.length - 1);
        return parastring;
}

function ajax(requesturl,data,type,isasync,successback,errorback)
{ 
	if (typeof data !== 'string') {
        data = JSON.stringify(data);
   }
	$.ajax({
		url: requesturl+data,
		//data: data,
		type: type,
		async: isasync,
		dataType: 'json',
		contentType: "application/json",
		success: function(res) {	
			if(successback)
				successback(res);
		},
		error: function (request, textStatus, errorThrown) {
			if(errorback)
				errorback(request,textStatus,errorThrown);
		}
	});
}
